// store/index.js
import { createStore } from 'vuex';

const store = createStore({
  state: {
	user:uni.setStorageSync('user'),
	openid: uni.getStorageSync("openid"),
	sessionKey: '',
    count: 1,
    cart: [], // 原有的购物车状态
    products: uni.getStorageSync('products') || [], // 初始化时从本地存储读取
	address:uni.getStorageSync("address")
  },
  mutations: {
		add(state, count) {
		  state.count = count;
		},
		setCart(state, items) {
		  // 更新购物车状态
		  state.cart = items;
		},
		Setaddress(state, address) {
		  state.address = address;
		  uni.setStorageSync("address",address)
		},
		SetOpenid(state, user) {
			 state.openid = user.openid;
		  uni.setStorageSync("openid",user.openid)
		},
		Setuser(state, payload) {
			  state.user = {
				  ...payload,
				  userId: payload.customerId ,
				   userName: payload.customerName
				};
				uni.setStorageSync("user", state.user);
		},
		addProduct(state, item) { // 添加或更新产品
			let existingItemIndex = state.products.findIndex(prod => prod.barcode === item.barcode);   
			if (existingItemIndex !== -1) {
				state.products[existingItemIndex].qutity += item.qutity;
			} else {
				state.products.push(item);
			}
			 uni.setStorageSync('products', state.products); // 同步到本地存储
		},
		clearProducts(state) { // 清空 products 并同步到本地存储
			state.products = [];
			uni.removeStorageSync('products');
		},
		updateProduct(state, updatedProduct) { // 更新某个产品的详细信息
			let index = state.products.findIndex(p => p.barcode === updatedProduct.barcode);
			if (index !== -1) {
				state.products[index] = { ...state.products[index], ...updatedProduct };
				uni.setStorageSync('products', state.products); // 同步到本地存储
			}
		},
		removeProduct(state, productId) { // 根据 productId 移除产品
			const index = state.products.findIndex(p => p.productId === productId);
			if (index !== -1) {
				state.products.splice(index, 1); // 从数组中移除商品
			}
			uni.setStorageSync('products', state.products); // 同步到本地存储
		}
	},
	actions: {
		addProduct({ commit }, item) {
			commit('addProduct', item);
			},
		clearProducts({ commit }) {
			commit('clearProducts');
		},
		updateProduct({ commit }, updatedProduct) {
			commit('updateProduct', updatedProduct);
		},
		removeProduct({ commit }, productId) {
			commit('removeProduct', productId);
		},
	  updateCart({ commit }, items) {
			commit('setCart', items);
	  },
		setAddress({ commit }, address) { // 确保这里与 dispatch 调用时的名字一致
		   commit('Setaddress', address);
		},
		  dologin(context, user) {
		    return new Promise((resolve, reject) => {
		      // #ifdef MP-WEIXIN
		      wx.login({
		        success: (loginRes) => {
		          if (!loginRes.code) {
		            reject(new Error('微信登录失败'));
		            return;
		          }
		
		          wx.request({
		            url: 'http://192.168.137.1:15000/USER-SERVICE/customer/login',
		            method: 'GET',
		            data: { code: loginRes.code },
		            success: (apiRes) => {
		              if (apiRes.data?.code === 200) {
		                const responseData = apiRes.data.data || {};
						const { customerId, customerName } = apiRes.data.data
		                context.commit("SetOpenid", responseData.data);
		               context.commit("Setuser", { customerId, customerName });
		                resolve(responseData); // 通知外部已完成
		              } else {
		                reject(new Error('服务器返回错误'));
		              }
		            },
		            fail: (err) => reject(new Error('API请求失败'))
		          });
		        },
		        fail: (err) => reject(new Error('wx.login失败'))
		      });
		      // #endif
		    });
		  }
	},
	getters: {
		getCart: state => state.cart,
		getProducts: state => state.products
	}
});

export default store;